﻿using System;
using System.Activities.Presentation;
using System.Windows;

namespace Headsight.BPMN2WF.WF.Impl
{
    public class WFBeautifier
    {
        private readonly WFWorkflowDesigner _wfWorkflowDesigner;

        public WFBeautifier(WorkflowDesigner workflowDesigner)
        {
            _wfWorkflowDesigner = new WFWorkflowDesigner(workflowDesigner);
        }

        public WorkflowDesigner Beautify()
        {
            var flowChartItem = _wfWorkflowDesigner.FlowChartItem;

            //var h = _wfWorkflowDesigner.ViewStateService.RetrieveViewState(flowChartItem.InnerItem, "Height");
            //var height = (h == null ? 0.0 : (Double)h);
            //var w = _wfWorkflowDesigner.ViewStateService.RetrieveViewState(flowChartItem.InnerItem, "Width");
            //var width = (w == null ? 0.0 : (Double)w);

            // Set Location and Size of Flowchart's start shape
            flowChartItem.ShapeLocation = new Point(300, 2.5);

            // First extend Size of FlowChart Item to fit all items.
            _wfWorkflowDesigner.ViewStateService.StoreViewStateWithUndo(flowChartItem.InnerItem, "Height", (Double)5000);
            _wfWorkflowDesigner.ViewStateService.StoreViewStateWithUndo(flowChartItem.InnerItem, "Width", (Double)3000);

            var lastItemPosition = FixPositionAndConnectors(flowChartItem);
            _wfWorkflowDesigner.ViewStateService.StoreViewStateWithUndo(flowChartItem.InnerItem, "Height", lastItemPosition.Y + 80);
            _wfWorkflowDesigner.ViewStateService.StoreViewStateWithUndo(flowChartItem.InnerItem, "Width", lastItemPosition.X + 80);

            return _wfWorkflowDesigner.WorkflowDesigner;
        }

        private Point FixPositionAndConnectors(AbstractModelItem currentItem)
        {
            currentItem.AlignChildren();
            currentItem.ResetConnector();

            var size = new Point();
            // Recursive step through Child Items
            foreach (var child in currentItem.ImmediateChildren)
                size = FixPositionAndConnectors(ModelItemFactory.Create(child, _wfWorkflowDesigner.ViewStateService, _wfWorkflowDesigner.WfActivityDesigner.ViewService));
            return size;
        }
    }
}
